/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.MarcasNeumatico;
import com.camachosanchez.controler.jdbc.MarcasNeumaticosJdbcControler;
import com.camachosanchez.controler.jpa.MarcasNeumaticoJpaController;
import com.camachosanchez.util.EstadosJDialog;
import com.camachosanchez.util.GUIUtil;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;

/**
 *
 * @author Zully
 */
public class EditorMarcaNeumatico extends javax.swing.JDialog {

    public EstadosJDialog.EstadoJDialog Estado;
    private MaestroMarcasNeumaticos buscador;
    private int fila;
    private MarcasNeumatico marca;
    
    /**
     * Creates new form EditorMarcaNeumatico
     */
    public EditorMarcaNeumatico(MaestroMarcasNeumaticos buscador, java.awt.Frame parent, boolean modal, MarcasNeumatico marca, int fila) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        GUIUtil.addEscapeKey(this);
        this.buscador = buscador;
        this.fila = fila;
        if (marca != null) {
            this.CargarDatosMarca(marca);
            this.marca = marca;
        }
        txtNombre.requestFocusInWindow();
    }
    
    private void CargarDatosMarca(MarcasNeumatico marca) {
        txtNombre.setText(marca.getNombre());
        txtIniciales.setText(marca.getIniciales());
    }
    
    public EstadosJDialog.EstadoJDialog getEstado() {
        return Estado;
    }

    public void setEstado(EstadosJDialog.EstadoJDialog Estado) {
        switch (Estado) {
            case NUEVO:
                btnEliminar.setVisible(false);
                break;
            case MODIFICAR:
                btnEliminar.setVisible(true);
                break;
        }
        this.Estado = Estado;
    }
    
    private void GuardarDatos() {
        switch (this.Estado) {
            case NUEVO:
                this.RegistrarMarca(this.LeerDatosMarca());
                break;
            case MODIFICAR:
                this.ModificarMarca(this.LeerDatosMarca());
                break;
            case ELIMINAR:
                break;
            default:
                break;
        }
    }

    private boolean ValidarDatos() {
        if (this.txtNombre.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Se requiere un nombre para la marca.", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
            txtNombre.requestFocusInWindow();
            return false;
        }
        if (this.txtIniciales.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Se requiere iniciales para la marca.", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
            txtIniciales.requestFocusInWindow();
            return false;
        }
        return true;
    }
    
    private MarcasNeumatico LeerDatosMarca() {
        MarcasNeumatico a = new MarcasNeumatico();
        a.setNombre(txtNombre.getText().trim());
        a.setIniciales(txtIniciales.getText().trim());
        if (this.marca != null) {
            a.setNeumaticosList(this.marca.getNeumaticosList());
        }
        return a;
    }
    
    private void RegistrarMarca(MarcasNeumatico marca) {
        MarcasNeumaticoJpaController dao_marca = new MarcasNeumaticoJpaController(null);
        marca.setEstado(true);
        dao_marca.create(marca);
        JOptionPane.showMessageDialog(this, "La marca ha sido guardada correctamente.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
        buscador.llenarMarcas();
        this.dispose();
    }

    private void ModificarMarca(MarcasNeumatico marca) {
        MarcasNeumaticoJpaController dao_almacen = new MarcasNeumaticoJpaController(null);
        try {
            marca.setEstado(true);
            marca.setId(this.marca.getId());
            dao_almacen.edit(marca);
            JOptionPane.showMessageDialog(this, "Los datos de la marca han sido actualizados correctamente.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
            buscador.llenarMarcas();
            dispose();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(Principal.getInstance(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlToolBar = new javax.swing.JPanel();
        btnGuardar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        pnlContenedor = new javax.swing.JPanel();
        lblNombre = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        lblIniciales = new javax.swing.JLabel();
        txtIniciales = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(".:: Marca de Neumático ::.");

        pnlToolBar.setBackground(new java.awt.Color(255, 255, 255));
        pnlToolBar.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_save.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnGuardar.setFocusable(false);
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnGuardar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        pnlToolBar.add(btnGuardar);

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_delete.png"))); // NOI18N
        btnEliminar.setToolTipText("Eliminar");
        btnEliminar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnEliminar.setFocusable(false);
        btnEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEliminar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnEliminar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnEliminar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });
        pnlToolBar.add(btnEliminar);

        getContentPane().add(pnlToolBar, java.awt.BorderLayout.PAGE_START);

        lblNombre.setText("<html>Nombre: <font color=\"red\">(*)</font> </html>");

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNombreKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        lblIniciales.setText("<html>Iniciales: <font color=\"red\">(*)</font> </html>");

        txtIniciales.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtInicialesKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtInicialesKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout pnlContenedorLayout = new javax.swing.GroupLayout(pnlContenedor);
        pnlContenedor.setLayout(pnlContenedorLayout);
        pnlContenedorLayout.setHorizontalGroup(
            pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlContenedorLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlContenedorLayout.createSequentialGroup()
                        .addComponent(lblIniciales, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtIniciales, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 186, Short.MAX_VALUE))
                    .addGroup(pnlContenedorLayout.createSequentialGroup()
                        .addComponent(lblNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)))
                .addContainerGap())
        );
        pnlContenedorLayout.setVerticalGroup(
            pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlContenedorLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtIniciales, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblIniciales, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        getContentPane().add(pnlContenedor, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
// TODO add your handling code here:
        if (ValidarDatos()) {
            GuardarDatos();
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        if (JOptionPane.showConfirmDialog(null, "¿Está seguro que desea eliminar esta marca?", "Confirmación", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
            int id = this.marca.getId();
                MarcasNeumaticosJdbcControler daoJdbc = new MarcasNeumaticosJdbcControler();
                byte estado = daoJdbc.eliminarMarca(id);
                if (estado == 1) {
                    JOptionPane.showMessageDialog(this, "La marca se encuentra relacionado con otros registros, no puede ser eliminada.", "Error en la eliminación", JOptionPane.ERROR_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, "La marca se ha eliminado de forma segura.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
                    buscador.borrarMarca(fila);
                    dispose();
                }
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void txtNombreKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyPressed
// TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            txtIniciales.requestFocusInWindow();
        }
    }//GEN-LAST:event_txtNombreKeyPressed

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
        // TODO add your handling code here:
//        char caracter = evt.getKeyChar();
        String caracteres = txtNombre.getText();
        if (caracteres.length() >= 45) {
            evt.consume();
        }
    }//GEN-LAST:event_txtNombreKeyTyped

    private void txtInicialesKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtInicialesKeyPressed
// TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            this.btnGuardar.requestFocusInWindow();
        }
    }//GEN-LAST:event_txtInicialesKeyPressed

    private void txtInicialesKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtInicialesKeyTyped
        // TODO add your handling code here:
        String caracteres = txtIniciales.getText();
        if (caracteres.length() >= 4) {
            evt.consume();
        }
    }//GEN-LAST:event_txtInicialesKeyTyped

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JLabel lblIniciales;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JPanel pnlContenedor;
    private javax.swing.JPanel pnlToolBar;
    private javax.swing.JTextField txtIniciales;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}
